#!/usr/bin/env python3

import quick2wire.i2c as i2c
import time

address = 0x20
iodir_register = 0x00
gpio_register = 0x09

def write_register(bus, reg, b):
    bus.transaction(
        i2c.writing_bytes(address, reg, b))
    
def read_register(bus, reg):
    return bus.transaction(
        i2c.writing_bytes(address, reg),
        i2c.reading(address, 1))[0][0]

with i2c.I2CMaster() as bus:    
    write_register(bus, iodir_register, 0x80)
    write_register(bus, gpio_register, 0x00)
    
    print("ready")
    
    button_down = False
    count = 0
    
    while True:
        gpio_state = read_register(bus, gpio_register)
        
        button_was_down = button_down
        button_down = bool(gpio_state & 0x80)
        
        if button_down and not button_was_down:
            count = min(count + 1, 127)
            write_register(bus, gpio_register, count)
        
        time.sleep(0.05)
